package cn.knight.org.service.impl;

import cn.knight.basic.constant.BaseConstants;
import cn.knight.basic.exception.BusinessException;
import cn.knight.basic.service.impl.BaseServiceImpl;
import cn.knight.basic.utils.BaiduAuditUtils;
import cn.knight.basic.utils.EmailUtils;
import cn.knight.org.domain.Employee;
import cn.knight.org.domain.Shop;
import cn.knight.org.domain.ShopAuditLog;
import cn.knight.org.mapper.EmployeeMapper;
import cn.knight.org.mapper.ShopAuditLogMapper;
import cn.knight.org.mapper.ShopMapper;
import cn.knight.org.service.IEmployeeService;
import cn.knight.org.service.IShopService;
import cn.knight.org.vo.ShopEchartVo;
import cn.knight.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author winnie
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private IEmployeeService EmployeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
    * @Title: settlement
    * @Description: 商铺入驻注册
    * @Author: winnie
    * @Version: 1.0
    * @Date:  1/7/2022 下午3:57
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    public void settlement(Shop shop) {
        // 前端传递的管理员对象
        Employee admin = shop.getAdmin();
        // 参数非空校验
        if (StringUtils.isEmpty(shop.getName())
                && StringUtils.isEmpty(shop.getAddress())
                && StringUtils.isEmpty(admin.getUsername())
                && StringUtils.isEmpty(admin.getPhone())
        ){
            throw new BusinessException("参数不能为空,请重新输入");
        }

        // 校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码不一致,请重新输入");
        }

        // AI校验店铺信息是否合规
        if (!BaiduAuditUtils.TextCensor(shop.getName()) || !BaiduAuditUtils.TextCensor(shop.getAddress())
            || !BaiduAuditUtils.TextCensor(admin.getUsername())
        ){
            throw new BusinessException("入驻信息违规，请输入合法信息！");
        }
        // AI校验图片是否合规
        String imageUrl = "http://123.207.27.208"+shop.getLogo();
        if (!BaiduAuditUtils.ImgCensor(imageUrl)){
            throw new BusinessException("图片信息违规，请输入合法信息！");
        }

        // 校验店铺是否存在，根据前端传递的店铺名来查询
        Shop loadShopTmp = shopMapper.loadByName(shop.getName());
        if (loadShopTmp != null){
            throw new BusinessException("店铺已注册，请重新输入");
        }

        // 校验管理员已存在，并且绑定了店铺
        Employee empTmp = employeeMapper.loadByUserName(admin.getUsername());
        if (empTmp != null){
            Shop shopAdminId = shopMapper.loadByAdminId(empTmp.getId());
            if (shopAdminId != null){
                throw new BusinessException("该管理员已经绑定了店铺，请重新输入");

            }
        }

        // 校验验证码是否正确
        // 根据业务键+phone作为key在redis中获取value
        String shopsettledCodeKey= BaseConstants.VerifyCodeConstant.BUSINESS_SHOPSETTLED_PREFIX+ admin.getPhone();
        Object shopsettledCodeValue = redisTemplate.opsForValue().get(shopsettledCodeKey);
        if (shopsettledCodeKey == null) {
            throw new BusinessException("验证码已过期，请重新获取");
        }
        String phoneValueRedis = shopsettledCodeValue.toString().split(":")[1];
        if (!phoneValueRedis.equalsIgnoreCase(admin.getSettledsmsCode())){
            throw new BusinessException("验证码错误，请重新输入");
        }

        // 管理员没有注册过，就添加到employee表中
        if (empTmp == null){
            EmployeeService.save(admin);
            empTmp = admin;
        }

        // 通过前面的校验，管理员已经注册上了，我们现在需要将店铺信息进行注册
        // 将管理员的主键ID赋值给shop的adminId
        shop.setAdminId(empTmp.getId());

        // 将店铺信息保存到数据库
        shopMapper.save(shop);

        // 将shop的主键ID赋值给empTmp的shopID
        empTmp.setShopId(shop.getId());

        // 修改员工表中的数据,给员工的shop_id赋值
        EmployeeService.update(empTmp);
    }


    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // 店铺状态：0待审核，1已审核，-1驳回，2待激活
        // 修改店铺状态为驳回状态'-1'
        Shop shopTmp = shopMapper.loadById(shopAuditLog.getShopId().longValue());
        shopTmp.setState(-1);
        shopMapper.update(shopTmp);

        //将驳回日志存入数据库
        String token = shopAuditLog.getToken();
        Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
        shopAuditLog.setAuditId(logininfo.getId().intValue()); // 没有做登录，操作人写死
        shopAuditLogMapper.save(shopAuditLog);

        // 查询管理员信息
        Employee admin = employeeMapper.loadById(shopTmp.getAdminId());

        // 发送邮件通知用户
        String subject = "店铺入驻审核状态";
        String url = "http://localhost:8081/#/register2?shopId="+shopAuditLog.getShopId();
        String text = "<h1>您好，您的店铺入驻申请信息已审核完毕，因内容不合规被驳回，请修改店铺信息后，再次申请!</h1><a href=" + url + ">" + url + "</a>";
        EmailUtils.sendMail(subject,text, admin.getEmail(),null,true);


    }
    /**
    * @Title: pass
    * @Description: 店铺入驻审核通过
    * @Author: winnie
    * @Version: 1.0
    * @Date:  2/7/2022 下午8:34
    * @Parameters:
    * @Return
    */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // 店铺状态：0待审核，1已审核，-1驳回，2待激活
        // 修改店铺状态为驳回状态'2'
        Shop shopTmp = shopMapper.loadById(shopAuditLog.getShopId().longValue());
        shopTmp.setState(2);
        shopMapper.update(shopTmp);

        //将驳回日志存入数据库
        String token = shopAuditLog.getToken();
        Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
        shopAuditLog.setAuditId(logininfo.getId().intValue()); // 没有做登录，操作人写死
        shopAuditLogMapper.save(shopAuditLog);

        // 查询管理员信息
        Employee admin = employeeMapper.loadById(shopTmp.getAdminId());

        // 发送邮件通知用户
        String subject = "店铺入驻审核状态";
        String url = "http://localhost:8080/shop/Enable/"+shopAuditLog.getShopId();
        String text = "<h1>审核通过，点击下方连接激活!</h1><a href=" + url + ">" + url + "</a>";
        EmailUtils.sendMail(subject,text, admin.getEmail(),null,true);

    }


    @Override
    public void not(ShopAuditLog shopAuditLog) {
        // 店铺状态：0待审核，1已审核，-1驳回，2待激活，-2拒绝
        // 修改店铺状态为拒绝状态'-2'
        Shop shopTmp = shopMapper.loadById(shopAuditLog.getShopId().longValue());
        shopTmp.setState(-2);
        shopMapper.update(shopTmp);

        //将驳回日志存入数据库
        shopAuditLog.setAuditId(325); // 没有做登录，操作人写死
        shopAuditLogMapper.save(shopAuditLog);

        // 查询管理员信息
        Employee admin = employeeMapper.loadById(shopTmp.getAdminId());

        // 发送邮件通知用户
        String subject = "店铺入驻审核状态";
        String text = "<h1>您好，您的店铺入驻申请信息因为违规已被拒绝，请在本平台注册页面重新进行入驻注册。</h1>";
        EmailUtils.sendMail(subject,text, admin.getEmail(),null,true);


    }

    /**
    * @Title: loadEcharts
    * @Description: 首页柱状体数据
    * @Author: winnie
    * @Version: 1.0
    * @Date:  3/7/2022 上午11:02
    * @Parameters: []
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> loadEcharts() {
        List<ShopEchartVo> shopEchartVos = shopMapper.loadEcharts();
        // 流式编程
        /* List<Integer> states = shopEchartVos.stream().map(ShopEchartVo::getState).collect(Collectors.toList());
        List<Integer> counts = shopEchartVos.stream().map(ShopEchartVo::getCount).collect(Collectors.toList()); */
        // 普通编程
        List<String> states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ShopEchartVo shopEchartVo : shopEchartVos) {
            // 店铺状态：0待审核，1已审核，-1驳回，2待激活，-2拒绝
            if (shopEchartVo.getState()== -1){
                states.add("驳回");
            } else if (shopEchartVo.getState() == 0){
                states.add("待审核");
            } else if (shopEchartVo.getState() == 1){
                states.add("已审核");
            } else if(shopEchartVo.getState() == 2){
                states.add("待激活");
            } else{
                states.add("拒绝");
            }
            counts.add(shopEchartVo.getCount());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("x", states);
        map.put("y", counts);
        return map;
    }


    @Override
    public void patchsave(List<Shop> shops) {
        shopMapper.patchsave(shops);
    }

    @Override
    public void Enable(Long id) {
        shopMapper.Enable(id);
    }



}
